'use strict';

const Controller = require('egg').Controller;

const createRule = {
  username: 'string',
  password: 'string',
  code: 'string',
};

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { sys } = ctx.service;
    ctx.validate({
      username: 'string',
      password: 'string',
    });
    try {
      const data = await sys.user.login(ctx.request.body);
      const { id, username, authToken, info, roles, resources } = data;
      ctx.set('Access-Token', `${authToken}`);
      ctx.set('Access-Control-Expose-Headers', 'Access-Token');
      ctx.success({
        data: { id, username, info, roles, resources },
      });
    } catch (error) {
      ctx.error({ detail: { type: 'account', message: error.message } });
    }
  }

  async logout() {
    const { ctx } = this;
    const { sys } = ctx.service;
    ctx.validate(createRule);
    try {
      const id = ctx.user.id;
      await sys.user.logout({ id });
      ctx.success({
        data: {},
      });
    } catch (error) {
      ctx.error({ detail: { message: error.message } });
    }
  }

  async index() {
    const ctx = this.ctx;
    const {
      sys: { user },
    } = ctx.service;
    const data = await user.find(ctx.query);
    ctx.success({ data });
  }

  async show() {
    const ctx = this.ctx;
    const {
      sys: { user },
    } = ctx.service;
    let { id } = ctx.params;
    if (id === 'current') {
      id = ctx.user.id;
    }
    const data = await user.findOne({ id });
    ctx.success({ data });
  }

  async create() {
    const ctx = this.ctx;
    const {
      sys: { user },
    } = ctx.service;
    ctx.validate(createRule);
    try {
      const id = await user.create(ctx.request.body);
      const data = {
        id,
      };
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async update() {
    const ctx = this.ctx;
    const {
      sys: { user },
    } = ctx.service;
    const params = Object.assign({ id: ctx.params.id }, ctx.request.body);
    const data = await user.update(params);
    ctx.success({ data });
  }

  async destroy() {
    const ctx = this.ctx;
    const {
      sys: { user },
    } = ctx.service;
    const data = await user.destroy(ctx.request.body);
    ctx.success({ data });
  }

  async setRole() {
    const ctx = this.ctx;
    const {
      sys: { user },
    } = ctx.service;
    const { id } = ctx.params;
    const { roleId } = ctx.request.body;
    const data = await user.update({ id, roleId });
    ctx.success({ data });
  }
}

module.exports = UserController;
